import time
import sys

# from .db import getLatestTest


def getNow():
    return time.strftime("%Y-%m-%d %H:%M:%S")


def getTimestamp(timeStr, format="%Y-%m-%d %H:%M:%S"):
    timeObj = time.strptime(timeStr, format)
    return time.mktime(timeObj)


# return date like 0902
def getDateStr(m, d):
    ls = [m, d]
    nls = [str(n) if int(n) >= 10 else "0" + str(n) for n in ls]
    date = "".join(nls)
    return date


# diff 为负数时，获取日期
def getDateForFuEasy(m, d, diff):
    nd = d + diff
    return getDateStr(m, nd)


def getDateForFu(m, d, diff):
    # 减少日期即可
    if d + diff > 0:
        return getDateForFuEasy(m, d, diff)
    else:
        cha = abs(d + diff)
        shang, yushu = divmod(cha, 30)
        # 借位，月份减少 日期增加
        jieWei = shang + 1
        m -= jieWei
        d = jieWei * 30 - cha
        return getDateStr(m, d)


# diff为正 获取日期
def getDateForZheng(m, d, diff):
    # 不需要进位 直接递增日期
    if d + diff <= 30:
        nd = d + diff
        return getDateStr(m, nd)
    else:
        # 需要进位 递增月份，减少日期
        shang, yushu = divmod(d + diff, 30)
        if yushu == 0:
            shang -= 1
            yushu = 30
        nm = m + shang
        nd = yushu
        return getDateStr(nm, nd)


def getNewDate(m, d, diff):
    if not m:
        m = time.strftime("%m")
    if not d:
        d = time.strftime("%d")

    m = int(m)
    d = int(d)
    diff = int(diff)
    if diff < 0:
        date = getDateForFu(m, d, diff)
    else:
        date = getDateForZheng(m, d, diff)
    return date


def getDateArg():
    # 命令行第一个位置参数为日期  python app.py date
    date = sys.argv[1] if len(sys.argv) >= 2 else "0"

    if date.lower() == "c":
        # 获取最新通关文件 words0908.txt
        # s = 'words0908.txt'
        # latestTest = getLatestTest("yang")
        latestTest = {}
        passfile = latestTest.passfile
        date = passfile.replace("words", "").replace(".txt", "")
        m = date[:2]
        d = date[2:]
        date = getNewDate(m, d, 1)

    if len(date) < 4:
        date = getNewDate(None, None, date)

    return date


if __name__ == "__main__":
    # print(getDate(9,12))
    # print(getDate(12,2))
    # main()
    print("test code here")
